'use strict'

const sha1 = require('sha1');
const getRowBody = require('raw-body')

const Wechat = require('./wechat');

module.exports = function (opts) {
  const wechat = new Wechat(opts);

  return function* (next) {
    // console.log('this.method: ', this.method);

    let token = opts.token;
    let signature = this.query.signature;
    let nonce = this.query.nonce;
    let timestamp = this.query.timestamp;
    let echostr = this.query.echostr;
    let str = [token, nonce, timestamp].sort().join("");
    let sha = sha1(str)

    if (this.method === 'GET') {
      if (sha === signature) {
        this.body = echostr;
      } else {
        this.body = 'wrong'
      }
    } else if (this.method === 'POST') {
      if (sha !== signature) {
        this.body = 'wrong';
        return false;
      } else {
        let data = yield getRowBody(this.req, {
          length: this.length,
          limit: '1mb',
          encoding: this.charset
        })

        console.log('data: ', data.toString());

      }
    }
  }
}
